package com.zwy.space.controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zwy.space.domain.BlogType;
import com.zwy.space.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.util.List;

@Controller
@RequestMapping("/admin/typesT")
public class TypeTController {

    @Autowired
    private TypeService typeService;

    @RequestMapping
    public String findTypesIndex(@RequestParam(defaultValue = "1",value = "pageNum") Integer pageNum, Model model){
        PageHelper.startPage(pageNum,10);
        List<BlogType> typeList=typeService.findAllTypesT();
        PageInfo<BlogType> pageInfo = new PageInfo<>(typeList);
        model.addAttribute("pageInfo",pageInfo);
        return "admin/typesT";
    }

    //    跳转修改分类页面
    @GetMapping("/{id}/input")
    public String editInput(@PathVariable int id, Model model) {
        model.addAttribute("type", typeService.getTypeT(id));
        return "admin/types-inputT";
    }

    //    编辑修改分类
    @PostMapping("/{id}")
    public String editPost(@Valid BlogType type, RedirectAttributes attributes) {
        BlogType type1 = typeService.getTypeByNameT(type.getName());
        if (type1 != null) {
            attributes.addFlashAttribute("message", "不能添加重复的分类");
            return "redirect:/admin/typesT/input";
        }
        int t = typeService.updateTypeT(type);
        if (t == 0 ) {
            attributes.addFlashAttribute("message", "编辑失败");
        } else {
            attributes.addFlashAttribute("message", "编辑成功");
        }
        return "redirect:/admin/typesT";
    }

    @RequestMapping("/{id}/delete")
    public String deleteType(@PathVariable int id, RedirectAttributes attributes){
        int t=typeService.deleteTypeByIdT(id);
        attributes.addFlashAttribute("message", "删除成功");
        return "redirect:/admin/typesT";
    }

    //    返回新增分类页面
    @GetMapping("/input")
    public String input(Model model){
        model.addAttribute("type", new BlogType());
        return "admin/types-inputT";
    }

    //  新增分类
    @PostMapping
    public String post(@Valid BlogType type, RedirectAttributes attributes) {
        BlogType type1 = typeService.getTypeByNameT(type.getName());
        if (type1 != null) {
            attributes.addFlashAttribute("message", "不能添加重复的分类");
            return "redirect:/admin/typesT/input";
        }
        int t = typeService.saveTypeT(type);
        if (t == 0) {
            attributes.addFlashAttribute("message", "新增失败");
        } else {
            attributes.addFlashAttribute("message", "新增成功");
        }
        return "redirect:/admin/typesT";
    }
}
